<?php

App::uses('AdminController', 'Controller');

class AdminHeadPhotosController extends AdminController {
	
	public $uses = array('Headphoto');
	
	private $headphoto_entities = array(
		"Novosti" => "Novosti",
		"Proizvodi" => "Kategorija proizvoda",
		"Recepti" => "Recepti",
		"Strana" => "Strana"
	);
	
	public function beforeFilter(){
		$this->set("headphoto_entities", $this->headphoto_entities);
	}
	
	public function index() {
		$this->set("headphotos", $this->Headphoto->find("all"));
	}
	
	public function create() {
		$this->render("form");
	}

	public function edit($id) {
		$this->set("headphoto", $this->Headphoto->findById($id));
		$this->render("form");
	}
	
	public function save() {
		if(!empty($this->data)) {
			$data = $this->data;
			
			$toupload = false;
			if(!$data['Headphoto']['image']['error']) {
				$toupload = $data['Headphoto']['image'];
				$data['Headphoto']['image'] = $toupload['name'];
			}else{
				$data['Headphoto']['image'] =$data['Headphoto']['image_original']; 
			}

			if($data['Headphoto']['type'] == "default") {
				if($toupload) {
					if($uploaded = upload($toupload['tmp_name'], 'img' . DS . 'headphotos' . DS . "default.jpg")){
						$this->setFlash("Podrazumevana slika u zaglavlju je promenjena", "ok");
					}else{
						$this->setFlash("Podrazumevana slika nije promenjena.");
					}
				}
			}else{
				unset($data['Headphoto']['type']);
				$this->set("headphoto", $data);
				
				$this->Headphoto->create($data);
				$this->Headphoto->set($data);
				
				if($this->Headphoto->validates()) {
					if($this->Headphoto->save($data)) {
						if($toupload) {
							upload($toupload['tmp_name'], 'img' . DS . 'headphotos' . DS . $toupload['name']);
						}
						$this->set("headphoto", $this->Headphoto->data);
						$this->redirect(array("action"=>"edit", $this->Headphoto->id));
					}else{
						$this->setFlash("Čuvanje nije uspelo.");
						return $this->render("form");
					}
				}else{
					$validationErrors = $this->Headphoto->validationErrors;
					$validationErrors = Set::extract($validationErrors, 'entity.{n}');
					$this->setFlash("Uneti podaci nisu validni. Čuvanje nije uspelo.<br>-" . implode("<br >-", $validationErrors));
					return $this->render("form");
				}
			}
		}
		$this->redirect("index");
	}
	
	public function delete($id) {
		$photo = $this->Headphoto->findById($id);
		if($photo) {
			if($this->Headphoto->delete($id)) {
				if(!empty($photo['Headphoto']['image'])) {
					@unlink("img" . DS . "headphotos" . DS . $photo['Headphoto']['image']);
				}
				$this->setFlash("Slika u zaglavlju je obrisana.", "ok");
			}
		}
		$this->redirect("index");
	}
	
}
